package wiki;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import com.Root;

/**
 * Servlet implementation class addissue
 */
public class AddIssue extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddIssue() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		
		
		Root root = new Root();
		ResultSet rs=null;
		ResultSet rs5 = null;
		ResultSet rs6 = null;
		PreparedStatement pst=null;

		try {

			String issuetitle = "";
			String issuedetails = "";
			String bugid = "";
			String version = "";
			String moduleid = "";
			String categoryid = "";
			String subcategoryid = "";
			String module = "";
			String category = "";
			String subcategory = "";
			String action = "";
			String user="";
			String corpuser="";
			
			issuetitle = request.getParameter("issuetitle");
			issuedetails = request.getParameter("issuedetails");
			bugid = request.getParameter("bugid");
			version = request.getParameter("version");
			moduleid = request.getParameter("moduleid");
			categoryid = request.getParameter("categoryid");
			subcategoryid = request.getParameter("subcategoryid");
			module = request.getParameter("module");
			category = request.getParameter("category");
			subcategory = request.getParameter("subcategory");
			user = request.getParameter("user");
			corpuser = request.getParameter("corpuser");

			action = request.getParameter("action");

			//System.out.println("CAtegory: " + category);

			
			
			String sql, sql1, sql5, sql6 = "";
			JSONObject issueinfo = null;

			int issueid = 0;

			//System.out.println("Version: " + version);

			
			version = version.replaceAll(",", "  ,  ");

			if ((issuetitle != null) || (!issuetitle.equals(""))) {

				if (action.equalsIgnoreCase("add")) {

					root.initConnection();
					int corpuserid =0;
					
					PreparedStatement pst5;
					String corpuserchk = corpuser;
					
					System.out.println("corpuser: " + corpuser);
					System.out.println("USER: " + corpuserchk);
					sql5="select * from corpusers where corpusername = ?;";
					pst5 = root.con.prepareStatement(sql5);
					pst5.setString(1, corpuserchk);
					rs5 = pst5.executeQuery();
					if (rs5.next()) {
						corpuserid = rs5.getInt("id");
						//System.out.println("ID: " + corpuserid);
					} else {
						System.out.println("Couldn't find user");
					}
					
					//System.out.println("user" + user);
					
					String[] uname = corpuser.split("\\.");
					String ufname = uname[0];
					String ulname = uname[1];

					//ufname = ufname.substring(0, 1).toUpperCase() + ufname.substring(1);
					//ulname = ulname.substring(0, 1).toUpperCase()+ ulname.substring(1);
					
					String initials = "";
					initials =  ufname.substring(0, 1).toUpperCase() + ulname.substring(0, 1).toUpperCase();
					//System.out.println("Initials:" + initials);
					
					user = ufname + ulname;
					
					//System.out.println("user" + user);
					
					PreparedStatement pst6;
					sql6="select issueidforuser as tempissueid from issue where createdby = ? order by id desc limit 1;";
					pst6 = root.con.prepareStatement(sql6);
					pst6.setString(1, user);
					
					int issueidofuser = 0;
					//System.out.println("query: " + sql6);
					rs6 = pst6.executeQuery();
					String temp1 ="";
					
					String tempissueid = "";
					int nxtissueidofuser = 0;
					
					if (rs6.next()) {
						//issueidofuser = rs6.getInt("issueidforuser");
						tempissueid = rs6.getString("tempissueid");
						
						String[] t1 = tempissueid.split("\\.");
						String tmpnid = t1[2];
						int t2 = Integer.parseInt(tmpnid);
						t2=t2+1;
						//System.out.println("t2= "+ t2);
						nxtissueidofuser = issueidofuser + 1;
						
						//System.out.println("nIssueid " + nxtissueidofuser);
						//String temp1 = Integer.toString(corpuserid) + "MC" + Integer.toBinaryString(issueidofuser);
						
						temp1 = String.format("%04d", corpuserid) + "." + initials + "."  + String.format("%04d", t2);
											
						//System.out.println("Temp1 =" + temp1);
						
						
					} else {
						//System.out.println("Couldn't find issue for user");
						
						int t2 = 1;
						temp1 = String.format("%04d", corpuserid) + "." + initials + "."  + String.format("%04d", t2);
						
						//System.out.println("Temp1 =" + temp1);
						
					}
					
					
					
					
					
					
					
					
					
					sql = "insert into issue "
							+ "(issuetitle, issuedetails, bugid, version, moduleid, categoryid, subcategoryid,module, category, subcategory,createdby,  issueidforuser, createdon )"
							+ "values (?, ?, ?,?,?, ? , ?,?, ?, ?,?,  ? ,CURRENT_DATE());";

					issuedetails=issuedetails.replaceAll("\\n", "<br/>");
					
					
					pst = root.con.prepareStatement(sql);
					pst.setString(1, issuetitle);
					pst.setString(2, issuedetails);
					pst.setString(3, bugid);
					pst.setString(4, version);
					pst.setString(5, moduleid);
					pst.setString(6, categoryid);
					pst.setString(7, subcategoryid);
					pst.setString(8, module);
					pst.setString(9, category);
					pst.setString(10, subcategory);
					pst.setString(11, user);
					//pst.setInt(12, nxtissueidofuser);
					pst.setString(12, temp1);
					

					// System.out.println("SQL: " + pst);
					pst.executeUpdate();

					PreparedStatement pst1;
					sql1 = "select LAST_INSERT_ID() as id";
					pst1 = root.con.prepareStatement(sql1);
					// System.out.println("SQL: " + pst1);
					rs = pst1.executeQuery();
					if (rs.next()) {
						//System.out.println("Found last_insert_id !");
						issueid = rs.getInt("id");
						//System.out.println("Issueid:" + issueid);
						issueinfo = new JSONObject();
						issueinfo.put("issueid", issueid);

						out.println("{\"issueinfo\": [" + issueinfo.toString()
								+ "]}");
					} else {
						//System.out.println("Couldn't find issue named "+ issueid);
					}

				}else if ( action.equalsIgnoreCase("update")){
					
					String editissueid = request.getParameter("issueid");
					root.initConnection();
					sql = "update issue set issuetitle= ?, issuedetails= ?, bugid= ?, version= ? , moduleid= ? , categoryid= ?, subcategoryid= ?," 
					+ " module= ?, category=?, subcategory= ? where id= ?" ;


					issuedetails=issuedetails.replaceAll("\\n", "<br/>");
					
					pst = root.con.prepareStatement(sql);
					pst.setString(1, issuetitle);
					pst.setString(2, issuedetails);
					pst.setString(3, bugid);
					pst.setString(4, version);
					pst.setString(5, moduleid);
					pst.setString(6, categoryid);
					pst.setString(7, subcategoryid);
					pst.setString(8, module);
					pst.setString(9, category);
					pst.setString(10, subcategory);
					pst.setString(11, editissueid);

					// System.out.println("SQL: " + pst);
					pst.executeUpdate();
				}else{
				}

			}
		} catch (Exception e) {
			System.out.println("Exception :" + e.toString());
		}finally{
			try {
				pst.close();
				rs.close();
				
				root.closeConnection();
			} catch (Exception e) {
				
			}
			
		}
	}

}
